package com.hongxin.nw.netty.utils;

import com.alibaba.fastjson.JSONObject;
import com.hongxin.nw.netty.utils.pools.ChannelPools;
import com.hongxin.nw.netty.values.StaticValue;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

/**
 * @remark 通道发送工具类
 * @author: GuoXiaolin
 * @date 2019/5/29 10:06
 * @Version 1.0
 * @Descibe
 */
@Slf4j
public class RequestCtx {
    //发送
    public static JSONObject sendCmdByAutoCid(Object msg, String code) throws Exception{
        ChannelHandlerContext ctx = ChannelPools.getCtx(code);
        if (ctx == null){
            return JSONUtils.getRoot(-1, "通道不存在", StaticValue.VAL_NULL);
        }
        if (!ctx.channel().isActive()){
            return JSONUtils.getRoot(-2, "通道不可用", StaticValue.VAL_NULL);
        }
        if (!ctx.channel().isOpen()){
            return JSONUtils.getRoot(-3, "通道已关闭", StaticValue.VAL_NULL);
        }
        if (msg instanceof String) {
            String str = (String) msg;
            log.info("<-{}", str);
            byte[] bytesWrite = BinaryTools.hexString2Bytes(str.trim());
            ByteBuf buf = ctx.alloc().buffer(bytesWrite.length/2);//Unpooled.buffer(bytesWrite.length/2);
            buf.retain();
            buf.writeBytes(bytesWrite);
            try {
                ChannelFuture cf = ctx.writeAndFlush(buf).sync().addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture channelFuture){}
                });
                if (cf.isSuccess()){
                    return JSONUtils.getRoot(0, "通道请求成功", str);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                buf.release();
            }
        }
        return JSONUtils.getRoot(-4, "通道请求失败", StaticValue.VAL_NULL);
    }
}
